<template>
  <div>
    <el-card>
      <div class="card-query">
        <div>
          <el-form class="form-query">
            <el-form-item>
              <el-input placeholder="关键字" v-model="keyword"></el-input>
            </el-form-item>
            <el-form-item class="btnQuery">
              <el-button
                icon="el-icon-search"
                type="primary"
                @click="handleQuery"
                >查找</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-button
            icon="el-icon-document-add"
            type="primary"
            @click="handleAdd"
            >添加</el-button
          >
          <el-button
            icon="el-icon-refresh"
            type="primary"
            @click="handleRefresh"
            >刷新</el-button
          >
        </div>
      </div>
    </el-card>

    <el-table :data="tableData" style="width: 100%" border stripe>
      <el-table-column label="Id" prop="id" width="50"> </el-table-column>
      <el-table-column
        label="用户名"
        prop="username"
        width="180"
      ></el-table-column>
      <el-table-column
        label="昵称"
        prop="nickname"
        width="180"
      ></el-table-column>
      <el-table-column label="头像" prop="avatar" width="180">
        <template slot-scope="scope">
          <el-avatar
            shape="square"
            size="medium"
            :src="showImage(scope.row.id)"
          ></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remarks"></el-table-column>
      <el-table-column label="操作" width="180px">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-edit"
            size="mini"
            type="primary"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <!-- <div>
            <el-popover placement="left" width="160" v-model="visible">
              <p>这是一段内容这是一段内容确定删除吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="visible = false"
                  >取消</el-button
                >
                <el-button type="primary" size="mini" @click="visible = false"
                  >确定</el-button
                >
              </div>
              <el-button slot="reference">删除</el-button>
            </el-popover>
          </div> -->

          <el-button
            icon="el-icon-delete"
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 模态框，用于用户的增加和修改 -->
    <el-dialog title="用户信息" :visible.sync="dialogFormVisible">
      <el-form :model="formData">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="formData.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="昵称" :label-width="formLabelWidth">
          <el-input v-model="formData.nickname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="头像" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :action="uploadActionUrl"
            :headers="uploadActionHeader"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="formData.avatarId"
              :src="dialogFormFullUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <!-- <el-input v-model="formData.avatar" autocomplete="off"></el-input> -->
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="formData.remarks" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分页组件 -->
    <div class="block">
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handlePageIndexChange"
        :current-page="pager.pageIndex"
        :page-size="pager.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pager.rowsTotal"
        background
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getList, addUser, modUser, delUser } from "../api/users";
import { getToken } from "../utils/auth";
import { showPicture } from "../utils/picture";
export default {
  data() {
    return {
      visible: false, //
      keyword: "", // 搜索的关键字
      tableData: [],
      pager: {
        pageIndex: 1,
        pageSize: 10,
        rowsTotal: 30,
      },
      dialogFormVisible: false,
      dialogFormFullUrl: "",
      formData: {
        id: 0,
        username: "",
        nickname: "",
        avatarId: 0,
        password: "113",
        remarks: "",
      },
      formLabelWidth: "120px",
      currentIndex: 0,
    };
  },
  mounted() {
    this.fetchData(this.pager);
  },
  methods: {
    handleQuery() {
      this.fetchData();
      this.$message.success("查找数据成功^_^");
    },
    handleRefresh() {
      this.fetchData();
      this.$message.success("刷新数据成功^_^");
    },
    // 用户添加
    handleAdd() {
      this.dialogFormVisible = true;
      this.formData.id = 0;
      this.formData.username = "";
      this.formData.password = "";
      this.formData.nickname = "";
      this.formData.avatar = "";
      this.formData.remarks = "";
    },
    // 用户修改
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.formData.id = row.id;
      this.formData.username = row.username;
      this.formData.nickname = row.nickname;
      this.formData.avatar = row.avatar;
      this.formData.remarks = row.remarks;

      // 编辑时获得当前表数组中的下标
      this.currentIndex = index;
      console.log(index, row);
    },
    // 删除用户
    handleDelete(index, row) {
      // 删除时获得当前表数组中的下标
      this.currentIndex = index;
      delUser(row.id)
        .then((res) => {
          console.log(res);
          if (res.code === 1000) {
            this.tableData.splice(index, 1);
            this.$message.success(res.msg);
          } else {
            this.$message({
              type: "info",
              message: res.msg,
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
      console.log(index, row);
    },
    // （无论是添加还是修改后）保存用户信息
    handleSave() {
      this.dialogFormVisible = false;
      console.log(this.formData);
      // 如果表单中的id为0，则认为是添加用户，反之则为修改用户
      if (this.formData.id === 0) {
        addUser(this.formData)
          .then((data) => {
            console.log(data);
            //将新添加的数据push到现有表数据的最后面
            this.tableData.push(data.data);
            this.$message.success(data.msg);
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        modUser(this.formData.id, this.formData)
          .then((data) => {
            console.log(data);
            this.tableData.splice(this.currentIndex, 1, data.data);
            this.$message.success(data.msg);
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    handleCancel() {
      this.dialogFormVisible = false;
    },
    // 页面页码改变时，重新拉取数据
    handlePageIndexChange(val) {
      console.log(val);
      this.pager.pageIndex = val > 0 ? val : 1;
      this.fetchData(this.pager);
    },
    // 页面大小改变时，重新拉取数据
    handlePageSizeChange(val) {
      console.log(val);
      this.pager.pageSize = val;
      this.fetchData(this.pager);
    },
    // 拉取后台数据（带分页）
    fetchData() {
      let params = {
        keyword: this.keyword,
        pager: this.pager,
      };
      getList(params).then((data) => {
        this.tableData = data.data.data;
        this.pager = data.data.pager;
      });
    },
    // 头像上传前的钩子函数，用于检测上传文件的大小、类型等
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 头像上传成功后调用的方法
    handleAvatarSuccess(res, file) {
      console.log(res);
      console.log(file);
      let fullPath = URL.createObjectURL(file.raw);
      this.formData.avatarId = res.data[0].id;
      this.dialogFormFullUrl = fullPath;
    },
    showImage(id) {
      let urlt = showPicture(id);
      console.log(urlt);
      return urlt;
    },
  },
  computed: {
    // 头像上传api接口需要token验证
    uploadActionHeader() {
      return {
        Authorization: "Bearer " + getToken(),
      };
    },
    // 头像上传的api地址
    uploadActionUrl() {
      let baseUrl = "http://localhost:5000/";
      let uploadUrl = "files/uploadfiles";
      return baseUrl + uploadUrl;
    },
  },
};
</script>
<style scoped>
.card-query,
.form-query {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.btnQuery {
  margin-left: 10px;
}
.form-query .el-form-item {
  margin-bottom: 0px;
}
/* 用户头像上传 */
.avatar-uploader .avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .avatar-uploader-icon:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>